package com.yuankun.chat.controller;

import com.yuankun.chat.server.ChatHistoryReposity;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.openai.OpenAiEmbeddingModel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.Arrays;

/**
 * @Author：yuankun
 * @Package：com.yuankun.chat.controller
 * @Project：chat
 * @name：ChatController
 * @Date：2025/8/17 16:20
 * @Filename：ChatController
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {
    private final ChatClient chatClient;
    private final ChatHistoryReposity chatHistoryReposity;
    private final OpenAiEmbeddingModel embed;

    @PostMapping("/chat")
    public Flux<String> chat(String prompt, String chatId) {
        //保存会话
        chatHistoryReposity.save("chat", chatId);
        return chatClient
                .prompt().user(prompt)
                .advisors(a->a.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream().content();
    }
    @GetMapping("/embed")
    public String embed() {
        return Arrays.toString(embed.embed("你是谁？"));
    }

    @GetMapping(value = "/stream/chat", produces = "text/text;charset=UTF-8")
    public Flux<String> StreamChat(String prompt) {
        return chatClient.prompt(prompt).user("你是谁？").stream().content();
    }
}
